package nl.jjsoft.airlock.controller
{
	import flash.filesystem.File;
	import flash.utils.ByteArray;
	
	import nl.jjsoft.airlock.SqlDB;
	import nl.jjsoft.airlock.domain.Model;
	import nl.jjsoft.airlock.domain.Session;
	import nl.jjsoft.airlock.utils.PasswordGenerator;
	import nl.jjsoft.airlock.view.Settings;
	import nl.jjsoft.airlock.vo.PasswordPolicyVo;
	
	public class SettingsController
	{
		[Inject]
		public var model:Model;
		
		[Inject]
		public var session:Session;		
		
		private var _db:SqlDB = null;
		
		public function SettingsController()
		{
		}
		
		private function get db():SqlDB {
			if (_db == null) {
				var dbFile:File = new File(session.dbFilePath);
				_db = new SqlDB();
				var key:ByteArray = PasswordGenerator.getEncryptionKey(session.safeCombination);
				_db.connect(dbFile, key);
			}
			return _db;
		}
		
		public function retrieveSettings():void {
			var query:String = 'SELECT id, length, useDigits, useLowerCase, useUpperCase, useSymbols FROM PasswordPolicy';
			var result:Array = db.select(query, null, PasswordPolicyVo);
			if (result != null && result.length > 0) {
				// settings previously stored, return settings
				model.passwordPolicy = result[0];
			} else {
				// settings not previously stored, create default settings
				model.passwordPolicy = new PasswordPolicyVo();
				saveSettings(model.passwordPolicy);
			}
		}
		
		public function saveSettings(passwordPolicy:PasswordPolicyVo):Boolean {
			var query:String = '';
			var params:Object = new Object();
			params[":length"] = passwordPolicy.length;
			params[":useLowerCase"] = passwordPolicy.useLowerCase;
			params[":useUppercase"] = passwordPolicy.useUpperCase;
			params[":useSymbols"] = passwordPolicy.useSymbols;
			params[":useDigits"] = passwordPolicy.useDigits;		
			
			// perform an update or a insert?
			if (isNaN(passwordPolicy.id)) { // INSERT
				query = 'INSERT INTO PasswordPolicy ([length], [useLowerCase], [useUppercase], [useSymbols], [useDigits]) ' + 
					'VALUES(:length, :useLowerCase, :useUppercase, :useSymbols, :useDigits)';
				passwordPolicy.id = db.insert(query, params);
			}
			else { // UPDATE (known group id)
				query = 'UPDATE PasswordPolicy' +
					' SET length=:length, useLowerCase=:useLowerCase, useUppercase=:useUppercase,' +
					'useSymbols=:useSymbols, useDigits=:useDigits'+
					' WHERE id=:id';
				params[":id"] = passwordPolicy.id;
				if (db.update(query, params) <= 0) {
					trace("An error occured when updating the group with id [" + passwordPolicy.id + "]");
					return false;
				}
			}
			
			return true;
		}
	}
}